(function () {
    //获取显示页面数据 服务器分页
	jQuery("#sInvoiceCustomerName").select2().trigger("change");
    jQuery("#sInvoicePeopleId").select2().trigger("change");
    var serverData = {};
    var	serverTable;
    jQuery(document).ready(function () {
        serverTable = jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/invoice/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
                {
                    data: null
                },
                {
                    data: null,
                    defaultContent: "",
                    render: function (data, type, full, meta) {
                        var id=data.contractId
                        var operate ='<input type="checkbox" class="checkchild">';
                        return operate;
                    }
                },
               
                {
                    data: 'sInvoiceIdentifyType',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 10) ? '<font title="'+data+'">'+data.substring(0,10)+'...'+'</font>' : data;
						}
					}
                },
               
                {
                    data: 'sInvoiceIdentify',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 15) ? '<font title="'+data+'">'+data.substring(0,15)+'...'+'</font>' : data;
						}
					}
                },
                {
                	data: 'nInvoiceActualPrice'
                },
                {
                	data: 'nBeLeftOverPrice'
                },
                {
                	data: 'rateValue'
                },
                /*{
                    data: 'sInvoiceAccount',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 15) ? '<font title="'+data+'">'+data.substring(0,15)+'...'+'</font>' : data;
						}
					}
                },*/
                {
                    data: 'sInvoiceCustomerName'
                },
                {
                    data: 'sInvoiceCustomerAccount'
                },
                /*{
                	data: 'sInvoiceTradeType'
                },*/
                {
                	data: 'sInvoicePeopleName'
                },
                {
                    data: 'dInvoiceDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY-MM-DD');
                        else
                            return '';
                    }
                },
                {
                	data: 'dInvoiceEffectiveDate',
                	render: function (data, type, full, meta) {
                		if (data)
                			return moment(data).format('YYYY-MM-DD');
                		else
                			return '';
                	}
                },
                {
                	data: 'sInvoiceMemo'
                },
            ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }
            }
        });
    });
    //查询
    jQuery('.searchBtn').on('click',function(){
        serverData.key=jQuery('#search').val();
        serverTable.draw();
    })
    //撤销查询
    jQuery('.resetBtn').on("click",function()
    {
        jQuery('#search').val('');
        serverData.key ='';
        serverTable.draw();
    });
    
    jQuery('.readBtn').on('click', function () {
        var selects=getSelect("#dataTable",1);
        if(selects.length>1){
            $.springLemonDialog({
                content: '只能查看一条记录',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }
        else if(selects.length==0){
            $.springLemonDialog({
                content: '请选择要查看的记录',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }else if(selects.length==1){
            jQuery('#id1').val(selects[0].id);
            jQuery('#sInvoiceIdentifyType1').val(selects[0].sInvoiceIdentifyType);
            jQuery('#sInvoiceIdentify1').val(selects[0].sInvoiceIdentify);
            //jQuery('#sInvoiceName1').val(selects[0].sInvoiceName);
            //jQuery('#sInvoiceAccount1').val(selects[0].sInvoiceAccount);
            jQuery('#sInvoiceIdentify1').val(selects[0].sInvoiceIdentify);
            jQuery('#sInvoiceIdentify1').val(selects[0].sInvoiceIdentify);
            jQuery('#nInvoiceActualPrice1').val(selects[0].nInvoiceActualPrice);
            jQuery('#sInvoiceCustomerName1').val(selects[0].sInvoiceCustomerId);
            //jQuery("#sInvoiceCustomerName1").select2().trigger("change");
            jQuery('#sInvoiceCustomerAccount1').val(selects[0].sInvoiceCustomerAccount);
            //jQuery("#sInvoiceCustomerAccount1").select2().trigger("change");
            //jQuery('#sInvoiceTradeType1').val(selects[0].sInvoiceTradeType);
            jQuery('#sInvoiceMemo1').val(selects[0].sInvoiceMemo);
            jQuery('#dInvoiceEffectiveDate1').val(selects[0].dInvoiceEffectiveDate);
            jQuery('#sInvoicePeopleId1').val(selects[0].sInvoicePeopleId);
    		jQuery("#sInvoicePeopleId1").select2().trigger("change");
            palnAmount=jQuery('#nInvoiceActualPrice1').val();
            amountOld= parseFloat(palnAmount);
            /*var result=amountOld/paySum;
            var operate=paySum <= 0 ? "0%" : (Math.round(result * 10000)/100).toFixed(2) + '%';*/
            //jQuery('#ratio').val(operate);
            if(selects[0].dInvoiceDate){
            var time=moment(selects[0].dInvoiceDate).format('YYYY-MM-DD');
            jQuery('#dInvoiceDate1').val(time);
            }
            else{
                jQuery('#dInvoiceDate1').val("");
            }
            //oldDate=jQuery('#payDate').val();
            jQuery('#paymentEditModalread').modal('show');
            jQuery('#createTime1').val(selects[0].createTime);
        }
    });
    /*var sInvoiceCustomerAccount = "";
    jQuery("#sInvoiceCustomerName").change(function () {
        var sInvoiceCustomerName = $("#sInvoiceCustomerName").val();
        $.ajax({
            url: window.rootPath + "/ui/invoice/getcustomerpage?customerid=" + sInvoiceCustomerName,
            dataType: "JSON",
            //data: {'gradeId': grade},
            type: "GET",
            success:function (data) {
                var gradeNum= data.data.length;
                var option = "<option value=''></option>";
                if(gradeNum>0){
                    //$("#sInvoiceCustomerAccount").html(option);
                    for(var i = 0;i<gradeNum;i++){
                        option += "<option value='"+data.data[i].bankAccount+"'>"+data.data[i].bankAccount+"</option>";
                    }
                }
                $("#sInvoiceCustomerAccount").html(option);
                //$("#sInvoiceCustomerAccount").val(Id); //编辑时绑定
                $("#sInvoiceCustomerAccount").select2({ minimumResultsForSearch: -1 });//加载样式
                $("#sInvoiceCustomerAccount").val(sInvoiceCustomerAccount);
                $("#sInvoiceCustomerAccount").select2().trigger("change");
                sInvoiceCustomerAccount = "";
            },
            error:function(e) {
                layer.alert("系统异常，请稍候重试！");
            }
        });
    });*/
    jQuery('.editBtn').on('click', function () {
    	//$("#paymentEditForm").reset();
        var selects=getSelect("#dataTable",1);
        if(selects.length>1){
            $.springLemonDialog({
                content: '只能编辑一条记录',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }
        else if(selects.length==0){
            $.springLemonDialog({
                content: '请选择要编辑的记录',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }else if(selects.length==1){
        	
            jQuery('#id').val(selects[0].id);
            jQuery('#sInvoiceIdentifyType').val(selects[0].sInvoiceIdentifyType);
            jQuery('#sInvoiceIdentify').val(selects[0].sInvoiceIdentify);
            //jQuery('#sInvoiceName').val(selects[0].sInvoiceName);
            //jQuery('#sInvoiceAccount').val(selects[0].sInvoiceAccount);
            jQuery('#sInvoiceIdentify').val(selects[0].sInvoiceIdentify);
            jQuery('#sInvoiceIdentify').val(selects[0].sInvoiceIdentify);
            jQuery('#nInvoiceActualPrice').val(selects[0].nInvoiceActualPrice);
            $('#rateValue').val(selects[0].rateValue);
            
            //$("#sInvoiceCustomerName").find("option[text='" + selects[0].sInvoiceCustomerName + "']").attr("selected",true);  
            //$("#sInvoiceCustomerName option[text='" + selects[0].sInvoiceCustomerNameId + "']").attr("selected", true);
            jQuery('#sInvoiceCustomerName').val(selects[0].sInvoiceCustomerId);
            jQuery("#sInvoiceCustomerName").select2().trigger("change");
            sInvoiceCustomerAccount = selects[0].sInvoiceCustomerAccount;
            jQuery('#sInvoiceCustomerAccount').val(selects[0].sInvoiceCustomerAccount);
            //jQuery("#sInvoiceCustomerAccount").select2().trigger("change");
            //jQuery('#sInvoiceTradeType').val(selects[0].sInvoiceTradeType);
            jQuery('#sInvoiceMemo').val(selects[0].sInvoiceMemo);
            jQuery('#sInvoicePeopleId').val(selects[0].sInvoicePeopleId);
    		jQuery("#sInvoicePeopleId").select2().trigger("change");
            palnAmount=jQuery('#nInvoiceActualPrice').val();
            amountOld= parseFloat(palnAmount);
            /*var result=amountOld/paySum;
            var operate=paySum <= 0 ? "0%" : (Math.round(result * 10000)/100).toFixed(2) + '%';*/
            //jQuery('#ratio').val(operate);
            if(selects[0].dInvoiceDate){
	            var time=moment(selects[0].dInvoiceDate).format('YYYY-MM-DD');
	            jQuery('#dInvoiceDate').val(time);
            }
            else{
                jQuery('#payDate').val("");
            }
            if(selects[0].dInvoiceEffectiveDate){
            	var time=moment(selects[0].dInvoiceEffectiveDate).format('YYYY-MM-DD');
            	jQuery('#dInvoiceEffectiveDate').val(time);
            }
            else{
            	jQuery('#dInvoiceEffectiveDate').val("");
            }
            //oldDate=jQuery('#payDate').val();
            jQuery('#paymentEditModal').modal('show');
            jQuery('#createTime').val(selects[0].createTime);
        }
    });
    
    jQuery('.addBtn').on('click', function () {
    	jQuery('#id').val("");
        jQuery('#sInvoiceIdentifyType').val("");
        jQuery('#sInvoiceIdentify').val("");
        //jQuery('#sInvoiceName').val("");
        //jQuery('#sInvoiceAccount').val("");
        jQuery('#sInvoiceIdentify').val("");
        jQuery('#sInvoiceIdentify').val("");
        jQuery('#nInvoiceActualPrice').val("");
        jQuery('#sInvoiceCustomerName').val("");
        jQuery("#sInvoiceCustomerName").select2().trigger("change");
        jQuery('#sInvoiceCustomerAccount').val("");
        //jQuery("#sInvoiceCustomerAccount").select2().trigger("change");
        //jQuery('#sInvoiceTradeType').val("");
        jQuery('#sInvoicePeopleId').val(jQuery("#sInvoicePeople").val());
		jQuery("#sInvoicePeopleId").select2().trigger("change");
        palnAmount=jQuery('#nInvoiceActualPrice').val();
        /*amountOld= parseFloat(palnAmount);
        //var result=amountOld/paySum;
        var operate=paySum <= 0 ? "0%" : (Math.round(result * 10000)/100).toFixed(2) + '%';
        //jQuery('#ratio').val(operate);*/
        jQuery('#payDate').val("");
        //jQuery('#dInvoiceEffectiveDate').val("");
        //oldDate=jQuery('#payDate').val();
        jQuery('#memo').val("");
        jQuery('#paymentEditModal').modal('show');
        jQuery('#createTime').val(new Date());
        
    });
    jQuery('.chanceEditBtn').on('click', function () {
    	var selects=getSelect("#dataTable",1);
        if(selects.length < 1){
            $.springLemonDialog({
                content: '请选择需要修改生效时间的数据',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }else if(selects.length>0){
            	var ids=selects[0].id;
            	for(var i=1;i<selects.length;i++){
            		ids += ',' + selects[i].id;  
    		    }
            	jQuery('#dInvoiceEffectiveDate2').val(new Date());
            	jQuery('#ids').val(ids);
            	jQuery('#InvoiceEffectiveDateModal').modal('show');
        }
    	
    });
    jQuery('.savedInvoiceEffectiveDateBtn').on('click', function () {
    	var ids = jQuery('#ids').val();
    	var date = jQuery('#dInvoiceEffectiveDate2').val();
    	var d = new Date(date.replace(/-/g, "/"));
    	var url = window.rootPath+"/ui/invoice/updatedate/" + ids + "/" + d;
    	jQuery.ajax({
        	type : 'get',
        	url : encodeURI(url),
        	dataType : 'json',
        	contentType : 'application/json;charset=utf-8',
        	success : function(data) {
        		if(data.code == 0){
        			alert("修改失败！");
        		}else if(data.code == 1){
        			alert("修改成功！");
        			jQuery('#ids').val("");
        			jQuery('#InvoiceEffectiveDateModal').modal('hide');
            		serverTable.draw(true);
        		}
        	}
    	});
    });
    jQuery('.clearBtn').on('click', function () {
    	var selects=getSelect("#dataTable",1);
        if(selects.length < 1){
            $.springLemonDialog({
                content: '请选择需要修改生效时间的数据',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }else if(selects.length>0){
            	var ids=selects[0].id;
            	for(var i=1;i<selects.length;i++){
            		ids += ',' + selects[i].id;  
    		    }
        }
    	var url = window.rootPath+"/ui/invoice/cleardate/" + ids;
    	jQuery.ajax({
    		type : 'get',
    		url : encodeURI(url),
    		dataType : 'json',
    		contentType : 'application/json;charset=utf-8',
    		success : function(data) {
    			if(data.code == 0){
    				alert("清除失败！");
    			}else if(data.code == 1){
    				alert("清除成功！");
    				serverTable.draw(true);
    			}
    		}
    	});
    });
    
    jQuery('.delBtn').on('click', function () {
        var selects=getSelect("#dataTable",1);
        if(selects.length < 1){
            $.springLemonDialog({
                content: '请选择需要删除的数据',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }else if(selects.length>0){
        	var ids=selects[0].id;
        	for(var i=1;i<selects.length;i++){
        		ids += ',' + selects[i].id;  
		    }
        	$.springLemonDialog({
		         content: '确认删除'+selects.length+'条记录？',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		        	 if (index == 0) {
		        		 var url = window.rootPath+"/ui/invoice/delbyid/" + ids;
		             	jQuery.ajax({
		                    	type : 'get',
		                    	url : encodeURI(url),
		                    	dataType : 'json',
		                    	contentType : 'application/json;charset=utf-8',
		                    	success : function(data) {
		                    		if(data.code == 0){
		                    			alert("选择的数据中存在已经开票信息！不能删除！");
		                    		}else if(data.code == 1){
		                    			alert("删除成功！");
		                        		serverTable.draw(true);
		                    		}
		                    	}
		             	});
		        	 }
		             $(this).closeDialog(modal);
		         }
        	});  
        }
    });
    jQuery('.saveBtn').on('click', function () {
        if (jQuery("#paymentEditForm") && !jQuery("#paymentEditForm").Validform({
                tiptype : 3,
                showAllError : true
            }).check(false)) {
            return;
        };
        var id = jQuery('#id').val();
        var rateValue=$("#rateValue").val();
        var sInvoiceIdentifyType = jQuery('#sInvoiceIdentifyType').val();
        var sInvoiceIdentify=jQuery('#sInvoiceIdentify').val();
        //var sInvoiceName = jQuery('#sInvoiceName').val();
        //var sInvoiceAccount=jQuery('#sInvoiceAccount').val();
        var dInvoiceDate=jQuery('#dInvoiceDate').val();
        var nInvoiceActualPrice=jQuery('#nInvoiceActualPrice').val();
        var sInvoiceCustomerId=jQuery('#sInvoiceCustomerName').val();
        //var dInvoiceEffectiveDate=jQuery('#dInvoiceEffectiveDate').val();
        var sInvoiceCustomerName=jQuery('#sInvoiceCustomerName').find("option:selected").text();//jQuery('#sInvoiceCustomerName').val();
        var sInvoiceCustomerAccount=jQuery('#sInvoiceCustomerAccount').val();//jQuery('#sInvoiceCustomerAccount').find("option:selected").text();
        var sInvoiceMemo=jQuery('#sInvoiceMemo').val();
        //var sInvoiceTradeType=jQuery('#sInvoiceTradeType').val();
        var createTime=jQuery('#createTime').val;
        var sInvoicePeopleId=jQuery('#sInvoicePeopleId').val();
        jQuery(".saveBtn").attr("disabled", true);
        var d = {
            "id": id,
            "sInvoiceIdentifyType": sInvoiceIdentifyType,
            "sInvoiceIdentify": sInvoiceIdentify,
            //"sInvoiceName": sInvoiceName,
            //"sInvoiceAccount": sInvoiceAccount,
            "dInvoiceDate": dInvoiceDate,
            "nInvoiceActualPrice": nInvoiceActualPrice,
            "sInvoiceCustomerId": sInvoiceCustomerId,
            "sInvoiceCustomerName": sInvoiceCustomerName,
            "sInvoiceCustomerAccount": sInvoiceCustomerAccount,
            "sInvoiceMemo": sInvoiceMemo,
            //"sInvoiceTradeType": sInvoiceTradeType,
            "sInvoicePeopleId": sInvoicePeopleId,
            //"dInvoiceEffectiveDate": dInvoiceEffectiveDate,
            "createTime": createTime,
            "rateValue":rateValue
        };
        if(id == ""){
        	save();
        }else{
        	var url=window.rootPath+'/ui/invoice/isInitial/'+id;
        	jQuery.ajax({
                type: 'get',
                url: encodeURI(url),
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                success: function (data) {
                	if(data.code>nInvoiceActualPrice) {
                		alert("输入的回款金额小于已开票金额，请重新输入金额！");
                	}else if(data.code<=nInvoiceActualPrice){
                		save();
                	}
                }
        	});
        }
        function save(){
        	var url = window.rootPath + '/ui/invoice/updata';
            jQuery.ajax({
                type: 'post',
                url: encodeURI(url),
                data: JSON.stringify(d),
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                success: function (data) {
                	alert("保存成功！");
                	jQuery('#paymentEditModal').modal('hide');
                    serverTable.draw();
                    jQuery(".saveBtn").attr("disabled", false);
                }
            });
        }
    });
    
  //EXCEL导入
    jQuery('.importReplacementList').on("click",function(){
    	var root = window.rootPath;
		WebFilesUploader({
			_webuploader : {
				server : root + '/ui/invoice/import', 
				swf : root
						+ '/resources/poweradminjs/webupload/webfilesuploader/Uploader.swf',
				chunked:false,
				multiple : false,
				accept:{
					title : "EXCEL导入",
					extensions : "xls,xlsx"
				}
			}
		}, function(jsons) {
			serverTable.draw();
		});
		
		WebFilesUploader.uploader.on("uploadSuccess",function(file,res){
	    	alert(res.count);
	    });
    });
})();